package com.st.shopadmin.adapter;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class DefineAdapter implements WebMvcConfigurer {


    private ApplicationContext applicationContext;

    public DefineAdapter() {
        super();
    }
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("classpath:/templates/");
        viewResolver.setSuffix(".html");
        return viewResolver;
    }

    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        //System.out.println("setApplicationContext方法");
        this.applicationContext = applicationContext;
    }
    //这里是实现用户拦截的具体操作，类LoginInterceptor是用户登录拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       // System.out.println("addInterceptors方法");
        /*
         *  多个拦截器组成一个拦截器链
         *  excludePathPatterns 用户排除拦截
         *  addPathPatterns 用于添加拦截规则
         *  拦截规则：除了"/manage/user/to_login.do" 其他都拦截
         * */
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new LoginInterceptor());
        interceptorRegistration.addPathPatterns("/**");
        interceptorRegistration.excludePathPatterns("/manage/user/to_login.do");
        interceptorRegistration.excludePathPatterns("/manage/user/do_login.do");
        interceptorRegistration.excludePathPatterns("/index.do");
        interceptorRegistration.excludePathPatterns("/static/**");
        //super.addInterceptors(registry);
    }

    //可以方便的将一个请求映射成视图，无需书写控制器，addViewCOntroller("请求路径").setViewName("请求页面文件路径")
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/manage/user/").setViewName("to_login.do");
    }



    //自定义资源拦截路径可以和springBoot默认的资源拦截一起使用，但是我们如果自己定义的路径与默认的拦截重复，那么我们该方法定义的就会覆盖默认配置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");//
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

}

